#include "networkthread.h"
#include "iniconfig.h"

#include <QDebug>

#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/if.h>

NetworkThread::NetworkThread(QObject *parent) :
    QThread(parent)
{
    this->loop = false;
    this->ipset = false;
}

NetworkThread::~NetworkThread()
{
    this->loop = false;
    this->ipset = false;
    while(this->isRunning());
}

bool NetworkThread::networkDetect(QString &ifname)
{
    int retval = 0;
    int skfd = 0;
    struct ifreq ifr;

    skfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(0 > skfd)
    {
        return false;
    }

    strcpy(ifr.ifr_name, ifname.toLatin1().data());
    retval = ioctl(skfd, SIOCGIFFLAGS, &ifr);
    close(skfd);

    if(0 <= retval && ifr.ifr_flags & IFF_RUNNING)
    {
        return true;
    }
    return false;
}

bool NetworkThread::networkNewIP(QString &ifname, const char *ip, const char *netmask)
{
    QString setip = QString("/sbin/ifconfig %1 %2 netmask %3 up").arg(ifname).arg(ip).arg(netmask);
    qDebug() << "网络线程：正在设置IP地址，SHELL命令为" << setip.toLatin1().data();
    if(0 == system(setip.toLatin1().data()))
    {
        return true;
    }
    return false;
}

bool NetworkThread::networkNewGateWay(const char *gateway)
{
    QString delgw = QString("/sbin/route delete default");
    QString setgw = QString("/sbin/route add default gw %1").arg(gateway);
    qDebug() << "网络线程：正在设置默认网关，SHELL命令为" << setgw.toLatin1().data();
    system(delgw.toLatin1().data());
    if(0 == system(setgw.toLatin1().data()))
    {
        return true;
    }
    return false;
}

void NetworkThread::slot_SetUIIsOK(bool status)
{
    qDebug() << "网络线程：在slot_SetUIIsOK槽中收到主线程发来的信号，值为" << status;
    this->uiok = status;
    this->ipset = false;
}

void NetworkThread::stop(void)
{
    qDebug() << "网络线程：终止运行";

    this->loop = false;
    this->ipset = false;
}

bool NetworkThread::initNetwork(QString &name, QString &staticip, QString &staticnetmask, QString &staticgateway, QString &dns1, QString &dns2)
{
    qDebug() << "网络线程：开始初始化参数";

    if(!INIConfig::safeVoluation(this->ifname[0], name))
    {
        qCritical() << "网络线程：设置 this->ifname[0] 失败，传入的值为" << name;
        return false;
    }

    this->ifname[1].clear();
    this->ifname[1].append(this->ifname[0]).append(":1");

    this->ifname[2].clear();
    this->ifname[2].append(this->ifname[0]).append(":2");

    if(!INIConfig::safeVoluation(this->staticip, staticip))
    {
        qCritical() << "网络线程：设置 this->staticip 失败，传入的值为" << staticip;
        return false;
    }

    if(!INIConfig::safeVoluation(this->staticmask, staticnetmask))
    {
        qCritical() << "网络线程：设置 this->staticmask 失败，传入的值为" << staticnetmask;
        return false;
    }

    if(!INIConfig::safeVoluation(this->staticgw, staticgateway))
    {
        qCritical() << "网络线程：设置 this->staticgw 失败，传入的值为" << staticgateway;
        return false;
    }

    if(!INIConfig::safeVoluation(this->dns1, dns1))
    {
        qCritical() << "网络线程：设置 this->dns1 失败，传入的值为" << dns1;
        return false;
    }

    if(!INIConfig::safeVoluation(this->dns2, dns2))
    {
        qCritical() << "网络线程：设置 this->dns2 失败，传入的值为" << dns2;
        return false;
    }

    this->loop = true;

    qDebug() << "网络线程：参数初始化已经完成，返回主线程";
    return true;
}

bool NetworkThread::isInitOK(void)
{
    qDebug() << "网络线程：当前运行状态为" << this->loop;
    return this->loop;
}

void NetworkThread::run(void)
{
    // 等待UI通知就绪信号
    while(!this->uiok)
    {
        QThread::sleep(1);
    }

    qDebug() << "网络线程：主线程已经初始化完毕，开始执行既定任务，当前运行状态为" << this->loop;

    // 线程开始
    while(this->loop)
    {
        if(this->networkDetect(this->ifname[0]))
        {
            if(!this->ipset)
            {
                qDebug() << "网络线程：正在将" << this->ifname[0] << "IP地址设置为" << this->staticip;
                if(this->networkNewIP(this->ifname[0], this->staticip.toLatin1().data(), this->staticmask.toLatin1().data()))
                {
                    qDebug() << "网络线程：IP地址已经设置成功";
                    qDebug() << "网络线程：设置子网卡" << this->ifname[1] << "的IP地址，返回值为" << this->networkNewIP(this->ifname[1], "172.16.16.17", "255.255.255.248");
                    qDebug() << "网络线程：设置子网卡" << this->ifname[2] << "的IP地址，返回值为" << this->networkNewIP(this->ifname[2], "10.101.101.101", "255.255.255.252");
                    qDebug() << "网络线程：设置默认网关为" << this->staticgw << "，返回值为" << this->networkNewGateWay(this->staticgw.toLatin1().data());
                    this->ipset = true;
                }
                else
                {
                    qDebug() << "网络线程：IP地址已经设置失败，重新开始";
                    QThread::sleep(1);
                    continue;
                }
            }
            emit this->Network2UI_UpdateStatusSignal(0);
        }
        else
        {
            emit this->Network2UI_UpdateStatusSignal(1);
        }
        QThread::sleep(1);
    }

    qDebug() << "网络线程：已经终止";

}
